package com.nitty.cash.loop.ui.activity

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.nitty.cash.loop.R
import com.nitty.cash.loop.base.app.NittyStackManager
import com.nitty.cash.loop.common.CommonActivity
import com.nitty.cash.loop.databinding.UiOrderDetailsBinding
import com.nitty.cash.loop.event.NittyEventData
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.ui.adapter.OrderDetailsAccountAdapter
import com.nitty.cash.loop.ui.dialog.NittyOrderDetailsGuideDialog
import com.nitty.cash.loop.ui.contract.IViewContract
import com.nitty.cash.loop.ui.presenter.OrderDetailsPresenter
import com.nitty.cash.loop.utils.helper.NittyProcessHelper
import com.nitty.cash.loop.utils.shared.NittySharedHelper
import com.nitty.cash.loop.utils.shared.NittySharedKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.math.BigDecimal

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/12/19 10:57
 * @Annotation：订单详情
 */
class OrderDetailsAct: CommonActivity(),IViewContract.IOrderDetailsView {
    lateinit var binding: UiOrderDetailsBinding
    private var eventRemark = ""
    private var presenter: OrderDetailsPresenter? = null
    private var accountAdapter: OrderDetailsAccountAdapter? = null

    companion object {
        private const val INTENT_KEY_ORDERID = "orderId"
        fun start(context: Context,orderId: String) {
            val intent = Intent(context, OrderDetailsAct::class.java)
            intent.putExtra(INTENT_KEY_ORDERID, orderId)
            context.startActivity(intent)
        }
    }

    override fun getNittyRootView(): View? {
        binding = UiOrderDetailsBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initNittyView() {
        setNittyTitleBarColor(Color.parseColor("#FFFFFFFF"))
        setNittyTextTitleVisibility(View.GONE)
        setNittyBackBtnRes(R.mipmap.img_back_black)
        setNittyRightBtnRes(R.mipmap.img_customer_black)
        initOrderDetailsRefrashView()
        initOrderDetailsAccountRecyclerView()
        binding.orderDetailsLayout.visibility = View.INVISIBLE
    }

    override fun initNittyListener() {
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog(eventRemark)
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_CUSTOMER,eventRemark)
        }
    }

    override fun loadNittyData() {
        if (presenter == null){
            presenter = OrderDetailsPresenter(this)
        }
        showNittyLoading()
        presenter?.loadOrderDetailsAction()
    }

    /* 初始化刷新 */
    private fun initOrderDetailsRefrashView() {
        binding.orderDetailsRefreshView.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.orderDetailsRefreshView.setOnRefreshListener {
            presenter?.loadOrderDetailsAction()
        }
    }

    /**
     * 初始化Views
     */
    private fun initOrderDetailsAccountRecyclerView(){
        binding.rvReceiveAccount.isNestedScrollingEnabled = false
        binding.rvReceiveAccount.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.rvReceiveAccount.layoutManager = layoutManager
        accountAdapter = OrderDetailsAccountAdapter(binding.rvReceiveAccount)
        binding.rvReceiveAccount.adapter = accountAdapter!!
        binding.rvReceiveAccount.itemAnimator = DefaultItemAnimator()
        accountAdapter?.setOnItemChildClickListener { _, childView, position ->
            val item = accountAdapter!!.getItem(position)

        }
    }

    /**
     * 获取订单id
     */
    override fun getOrderId(): String{
        return intent.extras!!.getString(INTENT_KEY_ORDERID).toString()
    }

    /**
     * 共用Views
     */
    override fun showOrderDetailsCommonViews(obj: JSONObject) {
        //刷新订单列表 - 防止状态差异
        publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_ORDER_REFRESH))

        binding.textApplyAmount.text = BigDecimal(obj.optString("amount")).stripTrailingZeros().toPlainString()
        binding.textUnit.text = obj.optString("currency")
        binding.textApplyTerm.text = obj.optString("days")
        binding.orderDetailsLayout.visibility = View.VISIBLE
        showOrderDetailsGuideDialog()
    }

    /**
     * 审核中
     */
    override fun showOrderDetailsReviewingViews() {
        binding.imgOrderStatus.setImageResource(R.mipmap.nitty_order_details_inreviewing_icon)
        binding.textOrderStatus.text = getString(R.string.order_status_reviewing)
        binding.textOrderStatus.setTextColor(Color.parseColor("#FF5D9BFF"))

        val showApproveTime = getString(R.string.order_details_reviewing_approve_time)
        val showContactTime = getString(R.string.order_details_reviewing_contact_time)
        val showTips = String.format(getString(R.string.order_details_reviewing_tips),showApproveTime,showContactTime)
        val index1 = showTips.indexOf(showApproveTime)
        val index2 = showTips.indexOf(showContactTime)
        val spString = SpannableString(showTips)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFD5118")), index1, index1 + showApproveTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFD5118")), index2, index2 + showContactTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textOrderStatusTips.text = spString

        //显示收款账户列表
        binding.textOrderDetailsReceiveAccount.visibility = View.VISIBLE
        binding.rvReceiveAccount.visibility = View.VISIBLE
        presenter?.loadScoreCommentAction()
    }

    /**
     * 放款中
     */
    override fun showOrderDetailsDisbursingViews() {
        binding.imgOrderStatus.setImageResource(R.mipmap.nitty_order_details_disbursing_icon)
        binding.textOrderStatus.text = getString(R.string.order_status_disbursing)
        binding.textOrderStatus.setTextColor(Color.parseColor("#FFFFAE58"))
        binding.textOrderStatusTips.text = getString(R.string.order_details_disbursing_tips)

        //显示收款账户列表
        binding.textOrderDetailsReceiveAccount.visibility = View.VISIBLE
        binding.rvReceiveAccount.visibility = View.VISIBLE
        presenter?.loadScoreCommentAction()
    }

    /**
     * 已拒绝
     */
    override fun showOrderDetailsRejectedViews(obj: JSONObject) {
        binding.imgOrderStatus.setImageResource(R.mipmap.nitty_order_details_rejected_icon)
        binding.textOrderStatus.text = getString(R.string.order_status_rejected)
        binding.textOrderStatus.setTextColor(Color.parseColor("#FFFF4D14"))

        var againApplyDate = obj.optString("againApplyDate","")
        if (againApplyDate.isEmpty()){
            againApplyDate = NittyProcessHelper.getAuthApplyAgainDate()
        }
        binding.textOrderStatusTips.text = String.format(getString(R.string.order_details_rejected_tips),againApplyDate)

        //不显示收款账户
        binding.textOrderDetailsReceiveAccount.visibility = View.GONE
        binding.rvReceiveAccount.visibility = View.GONE
    }

    /**
     * 待还款
     */
    override fun showOrderDetailsRepayViews() {
        //显示待还款列表
        publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_SHOW_REPAY))
        launch(Dispatchers.Main){
            delay(1000)
            NittyStackManager.finishAllActivity(NittyTabAct::class.java)
        }
    }

    override fun showOrderDetailsWalletList(accountList: ArrayList<JSONObject>) {
        accountAdapter?.data = accountList
    }

    /**
     * 显示引导dialog
     */
    private fun showOrderDetailsGuideDialog(){
        val isShowGuide = NittySharedHelper.getNittySharedBoolean(NittySharedKey.NITTY_DIALOG_GUIDE_REFRESH_SHOW)
        if (isShowGuide){//已显示过
            return
        }
        NittySharedHelper.putNittySharedData(NittySharedKey.NITTY_DIALOG_GUIDE_REFRESH_SHOW,true)
        val guideDialog = NittyOrderDetailsGuideDialog(this,object : NittyOrderDetailsGuideDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
        })
        guideDialog.setCancelable(false)
        guideDialog.setCanceledOnTouchOutside(false)
        guideDialog.show()
    }

    override fun hiddenNittyLoading() {
        super.hiddenNittyLoading()
        binding.orderDetailsRefreshView.isRefreshing = false
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "OrderDetails Page ${getOrderId()}"
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_ORDER_DETAILS_START,eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_ORDER_DETAILS_END,eventRemark)
    }
}